from threading import Lock


class SockPuppet(object):
    def __init__(self):
        self.headers_is_valid = []
        self.len = 0
        self.lock = Lock()
        self.iter = 0
        self.headers_list = [{}]

    def set_list(self, headers_list):
        try:
            self.lock.acquire()
            self.headers_list = headers_list
            self.len = len(self.headers_list)
            for headers in self.headers_list:
                self.headers_is_valid.append(True)
        finally:
            self.lock.release()

    def add_headers(self, headers):
        self.headers_list.append(headers)
        self.headers_is_valid.append(True)
        self.len += 1

    def get_headers(self):
        try:
            self.lock.acquire()
            if len(self.headers_is_valid) == 0:
                self.add_headers({})
            if self.headers_is_valid[self.iter] is True:
                res = self.headers_list[self.iter]
                temp = self.iter
                self.iter = (self.iter + 1) % self.len
                return res, temp
            elif self.has_headers():
                while self.headers_is_valid[self.iter] is False:
                    self.iter = (self.iter + 1) % self.len
                res = self.headers_list[self.iter]
                temp = self.iter
                self.iter = (self.iter + 1) % self.len
                return res, temp
            else:
                return None, -1

        finally:
            self.lock.release()

    def has_headers(self):
        for v in self.headers_is_valid:
            if v is True:
                return True
        return False
        pass

    def get_headers_by_i(self, i):
        return self.headers_list[i]

    def set_headers_invalid(self, headers_i):
        try:
            self.lock.acquire()
            self.headers_is_valid[headers_i] = False
        finally:
            self.lock.release()
